﻿using MapGeneration;
using PlayerRoles;
using PluginAPI.Core;
using PluginAPI.Core.Attributes;
using PluginAPI.Enums;
using PluginAPI.Events;
using RoundEvent.Main;
using System;
using System.ComponentModel;
using System.Linq;
using UnityEngine;
using Utils;



namespace RoundEvent.Event
{
    public class GreenEvent
    {
        string[] commands = new string[] { "event", "eve" };

        [PluginEvent(ServerEventType.RemoteAdminCommandExecuted)]
        public void OnRemoteCommandRun(RemoteAdminCommandExecutedEvent ev)
        {
            string command = ev.Command.ToLower();

            if (!commands.Contains(command)) return;

            if (ev.Arguments[0] != "green") return;


            if (ev.Arguments.Length == 1)
            {
                this.DoNoticeGreen();
                return;
            }


            if (ev.Arguments.Length == 2 && ev.Arguments[1] == "done")
            {
                TimeCoroutine.Stop(m_GreenCOR);
                this.DoNoticeGreenDone();
                return;
            }
        }

        [PluginEvent(ServerEventType.RoundStart)]
        public void OnRoundStart(RoundStartEvent ev)
        {
            TimeCoroutine.Stop(this.m_GreenCOR);
        }

        [PluginEvent(ServerEventType.RoundEnd)]
        public void OnRoundEnd(RoundEndEvent ev)
        {
            TimeCoroutine.Stop(this.m_GreenCOR);
        }





        [PluginEvent(ServerEventType.TeamRespawn)]
        public void OnTeamRespawn(TeamRespawnEvent ev)
        {
            if (Round.IsLocked) return;

            if (Warhead.IsDetonated) return;

            if (ev.Team != Faction.FoundationEnemy) return;

            bool isLucky = UnityEngine.Random.Range(0, 1f) <= CodeLoad.Singleton.Config.GreenEvent.HappenPercent;
            if (isLucky)
            {
                TimeCoroutine.Stop(m_GreenCOR);
                TimeCoroutine.Delay(60f, () => this.DoNoticeGreen());
            }
        }





        [Description("运行协程")] Coroutine m_GreenCOR;


        readonly Action act_Condition = () =>
        {
            var players = Player.GetPlayers().FindAll(e => e.IsAlive && e.Zone != FacilityZone.Surface);
            if (players.Count != 0)
            {
                players.ForEach(p =>
                {
                    if (p != null)
                    {
                        if (p.IsHuman)
                        {
                            if (p.Health <= CodeLoad.Singleton.Config.GreenEvent.HurtCountHuman)
                            {
                                p.SetRole(RoleTypeId.Spectator, RoleChangeReason.Died);
                                Cassie.Message("<color=#7DDA58>[绿色净网]</color> 程序执行中...（已清除一处人类污染）", true, true, true);
                            }

                            p.Damage(CodeLoad.Singleton.Config.GreenEvent.HurtCountHuman, "<color=#7DDA58>[绿色净网]</color>", "");
                        }

                        if (p.IsSCP && p.Role != RoleTypeId.Scp079)
                        {
                            if (p.Health <= CodeLoad.Singleton.Config.GreenEvent.HurtCountSCP)
                            {
                                p.SetRole(RoleTypeId.Spectator, RoleChangeReason.Died);
                                Cassie.Message("<color=#7DDA58>[绿色净网]</color>  程序执行中...（已清除一处<color=red>SCP</color>污染）", true, true, true);
                            }

                            p.Damage(CodeLoad.Singleton.Config.GreenEvent.HurtCountSCP, "<color=#7DDA58>[绿色净网]</color>", "");
                        }
                    }
                });
            }
        };

        private void DoNoticeGreen()
        {
            Cassie.Message("ATTENTION ALL PERSONNEL THE FORCE GREEN ZONE AS ANTI- Start");
            Cassie.Message("[协议三]<color=#7DDA58> 绿色净网</color> 开始执行 | 辐射腐蚀程序启动", false, false, true);

            Map.Rooms.ToList().FindAll(e => e.Zone != FacilityZone.Surface).ForEach(room =>
            {
                if (room.ApiRoom.TryGetComponent(out RoomLightController component, false, true))
                {
                    component.NetworkOverrideColor = new UnityEngine.Color(0.3f, 0.7f, 0.3f, 1f);
                }
            });

            this.DoMissionGreen();
        }
        private void DoNoticeGreenDone()
        {
            Cassie.Message("ATTENTION ALL PERSONNEL THE FORCE GREEN ZONE AS ANTI- Start");
            Cassie.Message("<color=#7DDA58>[绿色净网]</color> 程序已执行完毕....许可再进入", false, false, true);
        }


        private void DoMissionGreen()
        {
            TimeCoroutine.Stop(m_GreenCOR);
            m_GreenCOR = TimeCoroutine.Loop(
                CodeLoad.Singleton.Config.GreenEvent.Duration,
                CodeLoad.Singleton.Config.GreenEvent.Interval,
                act_Condition, 
                () => this.DoDoneGreen());
        }
        private void DoDoneGreen()
        {
            Map.Rooms.ToList().FindAll(e => e.Zone != FacilityZone.Surface).ForEach(room =>
            {
                if (room.ApiRoom.TryGetComponent(out RoomLightController component, false, true))
                {
                    component.NetworkOverrideColor = new UnityEngine.Color(1f, 1f, 1f, 0.1f);
                }
            });

            this.DoNoticeGreenDone();
        }
    }
}
